package com.gsbelarus.gedemin.salary.activity;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.lib.sync.protocol.SyncServiceModel;
import com.gsbelarus.gedemin.lib.sync.protocol.entity.SyncServiceStatus;
import com.gsbelarus.gedemin.lib.sync.protocol.entity.SyncServiceTask;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.SyncActivityDrawerModel;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.adapter.table.DrawerDivider;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.adapter.table.DrawerItem;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.adapter.table.DrawerMainItem;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.adapter.table.DrawerOtherItem;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.adapter.table.DrawerProfile;
import com.gsbelarus.gedemin.lib.ui.fragment.FragmentModel;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.SyncRequestType;
import com.gsbelarus.gedemin.salary.fragment.DrawerPersonInfoFragment;
import com.gsbelarus.gedemin.salary.fragment.SettingsFragment;
import com.gsbelarus.gedemin.salary.fragment.SplashFragment;
import com.gsbelarus.gedemin.salary.fragment.gdmsg.GdMsgsListFragment;
import com.gsbelarus.gedemin.salary.fragment.payslip.PayslipFragment;
import com.gsbelarus.gedemin.salary.fragment.statistic.StatisticDatesFragment;
import com.gsbelarus.gedemin.salary.fragment.workschedule.WorkScheduleFragment;
import com.gsbelarus.gedemin.salary.service.SyncService;
import com.gsbelarus.gedemin.salary.util.GCMHelper;

import io.realm.Realm;

public class Main extends SyncActivityDrawerModel implements SyncActivityDrawerModel.OnDrawerItemClickListener {

    public enum DrawerMenuItem {
        PAYSLIP, STATISTIC, WORKSCHEDULE, MAIL, SETTINGS
    }

    private static final String SPLASH_SCREEN_TAG = "splash_screen_tag";

    private String[] mainNamesDrawerMenu;

    private FragmentModel currentFragment;

    private RealmHelper realmHelper;

    @Override
    public int getContentResource() {
        return R.layout.activity_main;
    }

    @Override
    public void onReceiveSyncStatus(SyncServiceStatus syncServiceStatus, SyncStatusDialog syncStatusDialog) {
        super.onReceiveSyncStatus(syncServiceStatus, syncStatusDialog);
        syncStatusDialog.show(syncServiceStatus);
        if (syncServiceStatus.getTypeOfStatus() == SyncServiceStatus.TypeOfStatus.FINISH_SYNC) {

            Fragment splashScreen = getSupportFragmentManager().findFragmentByTag(SPLASH_SCREEN_TAG);
            if (splashScreen != null) {
                getSupportFragmentManager().beginTransaction().remove(splashScreen).commitAllowingStateLoss();
                selectMainItem(DrawerMenuItem.PAYSLIP.ordinal());
            }

            realmHelper.getRealm().refresh();
            updateMailCounter();
            updateProfileInfo();
            currentFragment.reloadFragmentData();
        }
    }

    @Override
    public void onCreateActivity(final Bundle savedInstanceState) {
        super.onCreateActivity(savedInstanceState);

        realmHelper = new RealmHelper(Realm.getInstance(context));
        mainNamesDrawerMenu = getResources().getStringArray(R.array.drawer_list);
        populateDrawer();

        setOnDrawerItemClickListener(this);

        if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SettingsFragment.WORK_MODE, false) &&
                realmHelper.getSyncInfo(true).getEmplId().isEmpty()
                && realmHelper.getLastEmployee() == null) {
            final SplashFragment splashFragment = new SplashFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, splashFragment, SPLASH_SCREEN_TAG).commit();

            startService(SyncServiceModel.getIntentWithTask(new Intent(context, SyncService.class),
                    SyncServiceTask.TypeOfTask.SINGLE_SYNC, new SyncRequestType(SyncRequestType.TypeOfRequest.DATA_MSG_REQUEST)));

        } else if (getIntent() != null && getIntent().hasExtra("openFragment") &&
                getIntent().getStringExtra("openFragment").equals(GdMsgsListFragment.class.getSimpleName()))
            selectMainItem(DrawerMenuItem.MAIL.ordinal());
        else
            selectMainItem(savedInstanceState.getLong("itemSelected", DrawerMenuItem.PAYSLIP.ordinal()));

        updateMailCounter();
        updateProfileInfo();

        Tracker tracker = ((App) getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());

        GCMHelper gcmHelper = new GCMHelper(context);
        gcmHelper.checkPlayServices(this);
        gcmHelper.checkRegistration();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().close();
    }

    private void populateDrawer() {
        final int resourceDrawable = R.drawable.drawer_wallpaper;
        final int resourceDrawableAccount = R.mipmap.ic_account_circle_white_48dp;
        setProfile(new DrawerProfile()
                .setText(getString(R.string.drawer_header_item_text))
                .setSummary(getString(R.string.drawer_person_info_action))
                .setProfileImage(getResources().getDrawable(resourceDrawableAccount))
                .setBackground(getResources().getDrawable(resourceDrawable))
                .setOnClickProfileInfoListener(new DrawerProfile.OnClickProfileInfoListener() {
                    @Override
                    public void onClick(View v) {
                        Intent drawerPersonInfoIntent = new Intent(Main.this, DrawerPersonInfo.class);
                        drawerPersonInfoIntent.putExtra(DrawerPersonInfoFragment.SAVE_RESOURCE_DRAWABLE, resourceDrawable);
                        drawerPersonInfoIntent.putExtra(DrawerPersonInfoFragment.SAVE_RESOURCE_DRAWABLE_ACCOUNT, resourceDrawableAccount);
                        startActivity(drawerPersonInfoIntent);
                    }
                })
                .setOnClickProfileImageListener(new DrawerProfile.OnClickProfileImageListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }));
        addItem(new DrawerMainItem(DrawerMenuItem.PAYSLIP.ordinal())
                .setImage(getResources().getDrawable(R.mipmap.ic_payslip2))
                .setText(mainNamesDrawerMenu[0])
                .setActivatedColor(getResources().getColor(R.color.toolbar)));
        addItem(new DrawerMainItem(DrawerMenuItem.STATISTIC.ordinal())
                .setImage(getResources().getDrawable(R.mipmap.ic_poll_box_grey600_24dp))
                .setText(mainNamesDrawerMenu[1])
                .setActivatedColor(getResources().getColor(R.color.toolbar)));
        addItem(new DrawerMainItem(DrawerMenuItem.WORKSCHEDULE.ordinal())
                .setImage(getResources().getDrawable(R.mipmap.ic_clock_grey600_24dp))
                .setText(mainNamesDrawerMenu[2])
                .setActivatedColor(getResources().getColor(R.color.toolbar)));
        addItem(new DrawerMainItem(DrawerMenuItem.MAIL.ordinal())
                .setImage(getResources().getDrawable(R.mipmap.ic_email_grey600_24dp))
                .setText(mainNamesDrawerMenu[3])
                .setCounter(0)
                .setActivatedColor(getResources().getColor(R.color.toolbar)));
        addItem(new DrawerDivider());
        addItem(new DrawerOtherItem(DrawerMenuItem.SETTINGS.ordinal())
                .setImage(getResources().getDrawable(R.mipmap.ic_settings_grey600_24dp))
                .setText(getResources().getString(R.string.action_settings)));
    }

    @Override
    public void onDrawerItemClick(DrawerItem item) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.mail_content);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        switch (DrawerMenuItem.values()[(int) item.getId()]) {
            case PAYSLIP:
                if (getSupportActionBar() != null)
                    getSupportActionBar().setTitle(mainNamesDrawerMenu[(int) getSelectedMainItem().getId()]);
                openFragment(new PayslipFragment());
                break;
            case STATISTIC:
                if (getSupportActionBar() != null)
                    getSupportActionBar().setTitle(mainNamesDrawerMenu[(int) getSelectedMainItem().getId()]);
                openFragment(new StatisticDatesFragment());
                break;
            case WORKSCHEDULE:
                openFragment(new WorkScheduleFragment());
                break;
            case MAIL:
                if (getSupportActionBar() != null)
                    getSupportActionBar().setTitle(mainNamesDrawerMenu[(int) getSelectedMainItem().getId()]);
                openFragment(new GdMsgsListFragment());
                break;
            case SETTINGS:
                Intent settingIntent = new Intent(Main.this, Settings.class);
                startActivity(settingIntent);
                break;
        }
        layout.setLayoutParams(params);
    }

    private void openFragment(FragmentModel fragment) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        if (currentFragment != null)
            fragmentTransaction.remove(currentFragment);
        currentFragment = fragment;
        fragmentTransaction.replace(R.id.mail_content, fragment);
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (getSelectedMainItem() != null)
            outState.putLong("itemSelected", getSelectedMainItem().getId());

        /** убираем сохраненный системой фрагмент */
        outState.remove("android:support:fragments");
    }

    /**
     * Обработка нажатий на пункты меню
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent settingIntent = new Intent(Main.this, Settings.class);
                startActivity(settingIntent);
                return true;
            case R.id.action_update:
                startService(SyncServiceModel.getIntentWithTask(new Intent(context, SyncService.class),
                        SyncServiceTask.TypeOfTask.SINGLE_SYNC, new SyncRequestType(SyncRequestType.TypeOfRequest.DATA_MSG_REQUEST)));
                return true;
            case android.R.id.home:
                /** Если фрагмент Почта, даем возможность переопределить действие на кнопку home */
                if (currentFragment instanceof GdMsgsListFragment)
                    return false;
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Создание меню (пункты Календарь, Обновить, Настройки)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sync, menu);
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void updateMailCounter() {
        DrawerItem item = getItemById(DrawerMenuItem.MAIL.ordinal());
        item.setCounter(realmHelper.getUnreadGdMsgsCount());
        notifyChangedItem(item);
    }

    public void updateProfileInfo() {
        DrawerProfile drawerProfile = realmHelper.getDrawerProfile();
        String text;
        if (drawerProfile != null) text = drawerProfile.getText();
        else text = getString(R.string.drawer_header_item_text);
        getProfile().setText(text);
        notifyChangedProfile();
    }

    @Override
    protected void onResume() {
        super.onResume();
        new GCMHelper(this).checkPlayServices(this);
    }
}